package com.ruoyi.system.outto.goods.impl;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.model.domain.AccountInfo;
import com.ruoyi.system.model.domain.InfoImg;
import com.ruoyi.system.model.domain.SalePartner;
import com.ruoyi.system.model.dto.GoodsInfoAndAttrValueDto;
import com.ruoyi.system.model.mapper.AccountInfoMapper;
import com.ruoyi.system.model.mapper.InfoImgMapper;
import com.ruoyi.system.outto.core.LCConstant;
import com.ruoyi.system.outto.core.MapSort;
import com.ruoyi.system.outto.core.MapUntils;
import com.ruoyi.system.outto.core.constant.GameTypeConstant;
import com.ruoyi.system.outto.game.CommonApi;
import com.ruoyi.system.outto.game.JYYAPI;
import com.ruoyi.system.outto.goods.IJYYAPI;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * @author lz
 * @version 1.0
 * @date 2022/8/16 22:58
 */
@Slf4j
@Service
public class JYYAPIImpl implements IJYYAPI {

    @Resource
    private CommonApi commonApi;
    @Value("${desc.title}")
    private String descTitle;

    @Resource
    private InfoImgMapper infoImgMapper;
    @Resource
    private AccountInfoMapper accountInfoMapper;

    /**
     * @param accountInfo
     * @param userId
     * @param operation   //(1,添加) (2,修改)(3,上下架)
     * @param isdel       是不是删除
     * @param salePartner
     * @return
     */
    @Override
    public AjaxResult addAndEditAndDelGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, Integer operation, boolean isdel, SalePartner sa) {
        Map<String, Object> resultMap = new HashMap<>();
        String url = sa.getTwoOther();
        Map<String, Object> params = params(goodsInfoAndAttrValueDto, sa);
        params.put("operation", operation);
        //（0，显示）（2，已下架）
        params.put("showSign", isdel ? 2 : 0);
        params.put("apiSuffix", sa.getSaleKey());
        String cover = MapUntils.getCover(params);
        cover = cover+"key=100033";
        String sign = DigestUtils.md5Hex(cover);
        params.put("sign",sign);
        String requestp = JSONObject.toJSONString(params);
        log.info("交易游{}( //(1,添加) (2,修改)(3,上下架))接口请求参数={}", operation, requestp);
        String result = null;
        try {
            result = HttpUtils.doPostForm(url, params, null);
        } catch (Exception e) {
            return getAjaxResult(resultMap, requestp, result);
        }
        log.info("交易游{}( //(1,添加) (2,修改)(3,上下架))接口返回参数={}", operation, result);

        return getAjaxResult(resultMap, requestp, result);
    }

    private SalePartner getSalePartner(Long userId) {
        SalePartner sa = commonApi.get(LCConstant.saleNameJYY, userId);
        if (Objects.isNull(sa)) {
            throw new GlobalException("合作伙伴未查到");
        }
        return sa;
    }


    private Map<String, Object> params(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner sa) {
        Map<String, Object> params = new TreeMap<>();
        String gameType = goodsInfoAndAttrValueDto.getGameName();
        String title = goodsInfoAndAttrValueDto.getDes();
        Long id = goodsInfoAndAttrValueDto.getId();
        String titleImg = goodsInfoAndAttrValueDto.getTitleImg();
        Integer gameId = getGameId(gameType);
        if (gameId == null) {
            log.error("游戏未找到{}", gameType);
            throw new GlobalException("游戏未找到" + gameId);
        }
        if(gameType.equals("王者荣耀")){
            String regional = goodsInfoAndAttrValueDto.getSystemName()+goodsInfoAndAttrValueDto.getCarrierName();
            if(regional.equals("安卓QQ")) {
                params.put("areaId", 108);
                params.put("serverId", 2388);
            }else if(regional.equals("安卓微信")) {
                params.put("areaId", 107);
                params.put("serverId", 2088);
            }else if(regional.equals("苹果微信")) {
                params.put("areaId", 106);
                params.put("serverId", 1788);
            }else{
                params.put("areaId", 105);
                params.put("serverId", 2688);
            }
        }
        if(gameType.equals("和平精英")){
            String regional = goodsInfoAndAttrValueDto.getSystemName()+goodsInfoAndAttrValueDto.getCarrierName();
            if(regional.equals("安卓QQ")) {
                params.put("areaId", 185);
                params.put("serverId", 8052);
            }else if(regional.equals("安卓微信")) {
                params.put("areaId", 185);
                params.put("serverId", 8051);
            }else if(regional.equals("苹果微信")) {
                params.put("areaId", 184);
                params.put("serverId", 8049);
            }else{
                params.put("areaId", 184);
                params.put("serverId", 8050);
            }
        }
        if(gameType.equals("枪战王者")){
            String regional = goodsInfoAndAttrValueDto.getSystemName()+goodsInfoAndAttrValueDto.getCarrierName();
            if(regional.equals("安卓QQ")) {
                params.put("areaId", 176);
                params.put("serverId", 4036);
            }else if(regional.equals("安卓微信")) {
                params.put("areaId", 176);
                params.put("serverId", 4035);
            }else if(regional.equals("苹果微信")) {
                params.put("areaId", 175);
                params.put("serverId", 4033);
            }else{
                params.put("areaId", 175);
                params.put("serverId", 4034);
            }
        }
        if(gameType.equals("原神")){
            if(goodsInfoAndAttrValueDto.getCarrierName().equals("游戏官方")){
                params.put("areaId", 282);
                params.put("serverId", 8102);
            }else{
                params.put("areaId", 330);
                params.put("serverId", 8527);
            }
        }
        params.put("gameId", gameId);
        params.put("goodsTypeId", 1);
        params.put("goodsNum", 1);
        params.put("bigTitle", "【" + descTitle + "_" + goodsInfoAndAttrValueDto.getId() + "】 " + title.replace("+",""));
        BigDecimal bigDecimal = commonApi.addPrice(goodsInfoAndAttrValueDto.getPrice(), sa.getSeleep());
        commonApi.setPrice(bigDecimal,goodsInfoAndAttrValueDto.getId(),sa);
        params.put("price", String.valueOf(bigDecimal));
        params.put("goodsDecs", goodsInfoAndAttrValueDto.getDes().replace("+",""));
        params.put("thumbnail", StringUtils.isEmpty(titleImg) ? "https://game.ikbh.top/logo/no_img.jpg" : titleImg);
        //图片
        StringBuilder imagesSb = new StringBuilder();
        InfoImg infoImg = new InfoImg();
        infoImg.setInfoId(id);
        infoImg.setType(Constants.STR_1);
        List<InfoImg> infoImgs = infoImgMapper.selectInfoImgList(infoImg);
        if (CollectionUtils.isEmpty(infoImgs)) {
        } else {
            for (InfoImg img : infoImgs) {
                imagesSb.append(img.getImgUrl()).append(",");
            }
        }
        params.put("goodsImages", StringUtils.isEmpty(imagesSb.toString()) ? "https://game.ikbh.top/logo/no_img.jpg" : imagesSb.toString());
        params.put("outSn", String.valueOf(id));
        return params;
    }

    private Integer getGameId(String game) {
        if (game.equals(GameTypeConstant.WZRY)) {
            return 3;
        } else if (game.equals(GameTypeConstant.HPJY)) {
            return 56;
        } else if (game.equals(GameTypeConstant.CF)) {
            return 5;
        } else if (game.equals(GameTypeConstant.LOL)) {
            return 4;
        } else if (game.equals(GameTypeConstant.YS)) {
            return 69;
        } else if (game.equals(GameTypeConstant.YJWJ)) {
            return 86;
        } else if (game.equals(GameTypeConstant.QZWZ)) {
            return 64;
        }
        return null;
    }

    /**
     * 公共参数
     *
     * @param sa
     */
    private Map<String, Object> doneCommonParms(SalePartner sa, Map<String, Object> params) {
        params.put("apiSuffix", sa.getSaleKey());
        List<Map.Entry<String, Object>> entries = new MapSort().sortMap(params);
        String key = sa.getOther();
        StringBuilder sb = new StringBuilder();
        HashMap<String, Object> newMap = new HashMap<>();

        for (final Map.Entry<String, Object> m : entries) {
            if (m.getValue() == null) {
                sb.append(m.getKey() + "=" + "1" + "&");
                newMap.put(m.getKey(), "1");
            } else {
                if (StringUtils.isEmpty(m.getValue().toString())) {
                    sb.append(m.getKey() + "=" + "1" + "&");
                    newMap.put(m.getKey(), "1");

                } else {
                    sb.append(m.getKey() + "=" + m.getValue().toString() + "&");
                    newMap.put(m.getKey(), m.getValue());
                }
            }

        }
//        String substring = sb.substring(0, sb.length() - 1);
        newMap.put("sign", DigestUtils.md5Hex(sb + "key=" + key));
        return newMap;
    }

    private static AjaxResult getAjaxResult(Map<String, Object> resultMap, String requestp, String result) {
        JSONObject resultJson = JSONObject.parseObject(result);
        if (resultJson != null) {
            if (!"0".equals(resultJson.getString("code"))) {
                resultMap.put("code", 500);
            } else {
                resultMap.put("code", 200);
            }
            resultMap.put("msg", resultJson.toJSONString());
        } else {
            resultMap.put("code", 500);
            resultMap.put("msg", "未知");
        }

        resultMap.put("req", requestp);
        resultMap.put("res", result);
        return AjaxResult.success(resultMap);
    }

    public static void main(String[] args) {

    }

}